import shutil
import time
from datetime import datetime
from wsgiref.handlers import format_date_time
import hashlib
import base64
import hmac
from urllib.parse import urlencode
import os
import traceback
import json
import requests

from utils import json_utils


class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg


class Url:
    def __init__(this, host, path, schema):
        this.host = host
        this.path = path
        this.schema = schema
        pass


# calculate sha256 and encode to base64
def sha256base64(data):
    sha256 = hashlib.sha256()
    sha256.update(data)
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')
    return digest


def parse_url(requset_url):
    stidx = requset_url.index("://")
    host = requset_url[stidx + 3:]
    schema = requset_url[:stidx + 3]
    edidx = host.index("/")
    if edidx <= 0:
        raise AssembleHeaderException("invalid request url:" + requset_url)
    path = host[edidx:]
    host = host[:edidx]
    u = Url(host, path, schema)
    return u


# build websocket auth request url
def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
    u = parse_url(requset_url)
    host = u.host
    path = u.path
    now = datetime.now()
    date = format_date_time(time.mktime(now.timetuple()))
    # print(date)
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)
    # print(signature_origin)
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    # print(authorization_origin)
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }

    return requset_url + "?" + urlencode(values)


def invoice_util(path):
    APIKey = "3ad055e0de46fa9ebf5afe0df94225a8"
    APPId = "31081998"
    APISecret = "M2MwYjcxMzEwOWVhNjA3MzNiN2U5ZDhl"
    # path = "D://test.png"
    w = open(path, 'rb')
    t = base64.b64encode(w.read())

    # url = 'https://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    url = 'http://iflydigita.api.xf-yun.com/v1/private/se9b136aa'

    body = {
        "header": {
            "app_id": APPId,
            "uid": "3976979589",
            "did": "SR08232194000020",
            "imei": "866402031869366",
            "imsi": "460026495272910",
            "mac": "6c:92:bf:65:c6:14",
            "net_type": "wifi",
            "net_isp": "CMCC",
            "status": 3,
            "request_id": ""
        },
        "parameter": {
            "se9b136aa": {
                "result": {
                    "encoding": "utf8",
                    "compress": "raw",
                    "format": "json"
                }
            }
        },
        "payload": {
            "default_request_data_1": {
                "encoding": "png",
                "image": str(t, 'UTF-8'),
                "status": 3
            }
        }
    }

    request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)

    headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
    # print(request_url)
    # print(json.dumps(body))
    response = requests.post(request_url, data=json.dumps(body), headers=headers)
    # print(response.json())
    st = response.json().get('payload').get('result').get('text')
    result = base64.b64decode(st).decode('utf-8')
    # print(result)
    # print(json.dumps(result,ensure_ascii=False))
    result = json.loads(result).get('response').get('data').get('identify_results')[0].get('details')
    # print(result)
    w.close()
    return result


if __name__ == "__main__":
    # APIKey = "3ad055e0de46fa9ebf5afe0df94225a8"
    # APPId = "31081998"
    # APISecret = "M2MwYjcxMzEwOWVhNjA3MzNiN2U5ZDhl"
    # path = "D://test.png"
    # w = open(path, 'rb')
    # t = base64.b64encode(w.read())
    #
    # # url = 'https://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    # url = 'http://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    #
    # body = {
    #     "header": {
    #         "app_id": APPId,
    #         "uid": "3976979589",
    #         "did": "SR08232194000020",
    #         "imei": "866402031869366",
    #         "imsi": "460026495272910",
    #         "mac": "6c:92:bf:65:c6:14",
    #         "net_type": "wifi",
    #         "net_isp": "CMCC",
    #         "status": 3,
    #         "request_id": ""
    #     },
    #     "parameter": {
    #         "se9b136aa": {
    #             "result": {
    #                 "encoding": "utf8",
    #                 "compress": "raw",
    #                 "format": "json"
    #             }
    #         }
    #     },
    #     "payload": {
    #         "default_request_data_1": {
    #             "encoding": "png",
    #             "image": str(t,'UTF-8'),
    #             "status": 3
    #         }
    #     }
    # }
    #
    # request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
    #
    # headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
    # # print(request_url)
    # # print(json.dumps(body))
    # response = requests.post(request_url, data=json.dumps(body), headers=headers)
    # # print(response)
    # st = response.json().get('payload').get('result').get('text')
    # result = base64.b64decode(st).decode('utf-8')
    # # print(json.dumps(result,ensure_ascii=False))
    # print(json.loads(result).get('response').get('data').get('identify_results')[0].get('details').get('code'))
    # w.close()

    # config = json_utils.get_json_by_path(r'D:\workspace\PycharmWorkSpace\PayAndReceiveAccounts\config\config.json')
    # ROOT_PATH = config['ROOT_PATH']
    path = "D://test//2.jpg"
    s = invoice_util(path)
    print(s)
    #
    # # 获取当前日期
    # # print(datetime.today())
    # now = time.localtime()
    # # now_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
    # now_time = time.strftime("%Y-%m-%d", now)
    #
    # # 创建文件夹
    # dstpath = os.path.join(ROOT_PATH, now_time)
    #
    # # 复制文件到指定文件夹
    # if not os.path.isfile(path):
    #     print("%s not exist!" % (path))
    # else:
    #     fpath, fname = os.path.split(path)  # 分离文件名和路径
    #     if not os.path.exists(dstpath):
    #         os.makedirs(dstpath)  # 创建路径
    #     shutil.move(path, os.path.join(dstpath, fname))  # 移动文件
    #     print("move %s -> %s" % (path, dstpath + fname))

    # s = "发票存在问题微信图片_20220516163531.jpg"
    # identify = ["查无此票", "已抵扣", "发票存在问题"]
    # t = False
    # for i in range(len(identify)):
    #     print(identify[i])
    #     if (identify[i] in s):
    #         t = True
    # print(t)
